package com.qcby.service.impl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.qcby.dao.BaseDao;
import com.qcby.service.BaseService;
import com.qcby.util.Page;

public class BaseServiceImpl<Q,T> implements BaseService<Q,T> {

    protected BaseDao<Q, T> baseDao;

    @Override
    public Integer insert(T t) {
        return baseDao.insert(t);
    }

    @Override
    public T selectByPrimaryKey(Integer id) {
        return baseDao.selectByPrimaryKey(id);
    }

    @Override
    public Integer deleteByPrimaryKey(Integer id) {
        return baseDao.deleteByPrimaryKey(id);
    }

    @Override
    public Integer updateByPrimaryKeySelective(T t) {
        return baseDao.updateByPrimaryKeySelective(t);
    }

    @Override
    public List<T> selectObjectAll() {
        return baseDao.selectObjectAll();
    }



    /**
     * @param q
     * @return
     */
    @Override
    public Page<T> selectObjectByCondition(Q q, String condition) {
        //获得查询对象的类对象
        Class<? extends Object> qclass = q.getClass();
        Page<T> page = new Page<T>();
        try {
            //获得getPageNo对象
            Method method = qclass.getMethod("getPageNo", null);
            //反射调用getPageNo方法
            Integer pageNo = (Integer) method.invoke(q, null);

            Method method2 = qclass.getMethod("getPageSize", null);
            //反射调用getPageNo方法
            Integer pageSize = (Integer) method2.invoke(q, null);
            //创建page对象
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
            //计算开始行号和结束行号
            Integer startNum = (pageNo - 1) * pageSize;
            //好的查询对象 的设置开始行号和结束行号的方法
            Method setStartNumMethod = qclass.getMethod("setStartNum", new Class[]{Integer.class});
            setStartNumMethod.invoke(q, startNum);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<T> list=new ArrayList<T>();
        Integer count=-1;
        //查询结果集
        //普通查询
        if ("0".equals(condition)) {
            list = baseDao.selectObjectByCondition(q);
            //查询指定查询条件下的总记录数
            count = baseDao.selectObjectByConditionCount(q);
        } else if ("1".equals(condition)) {
            list = baseDao.selectObjectByConditionRM(q);
            count = baseDao.selectObjectByConditionRMCount(q);
        } else if ("2".equals(condition)) {
            list = baseDao.selectObjectByConditionPF(q);
            count = baseDao.selectObjectByConditionPFCount(q);
        }else{
            list = baseDao.selectObjectByConditionScore(q);
            count = baseDao.selectObjectByConditionScoreCount(q);
        }

        //把总记录数设置给page对象
        page.setTotalCount(count);
        page.setList(list);
        return page;
    }

}